/**
 * Copyright 2014 Michail Basios
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import java.io.File;
import java.io.IOException;
import java.util.Arrays;

import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

public class Compile {

	public static void main(String args[], String folderPath)
			throws IOException {
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
		DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
		StandardJavaFileManager fileManager = compiler.getStandardFileManager(
				diagnostics, null, null);

		/* Prepare any compilation options to be used during compilation */
		// In this example, we are asking the compiler to place the output files
		// under bin folder.

		System.out
				.println("TO folder path gia to compile einai: " + folderPath);

		File binDir = new File(new File(folderPath).toString() + "/bin");
		System.out.println("To bin dir einai: " + binDir);
		if (!binDir.exists()) {

			binDir.mkdir();
		}

		String[] compileOptions = new String[] { "-d", folderPath + "/bin" };
		Iterable<String> compilationOptionss = Arrays.asList(compileOptions);

		Iterable<? extends JavaFileObject> compilationUnits = fileManager
				.getJavaFileObjectsFromStrings(Arrays.asList(args));
		JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager,
				diagnostics, compilationOptionss, null, compilationUnits);
		// boolean success = task.call();

		boolean status = task.call();

		if (!status) {// If compilation error occurs
			/* Iterate through each compilation problem and print it */
			for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
				System.out.format("Error on line %d in %s ",
						diagnostic.getLineNumber(), diagnostic);
				System.out.println();
			}
		}
		try {
			fileManager.close();// Close the file manager
		} catch (IOException e) {
			e.printStackTrace();
		}

		System.out.println("Success: " + status);

	}
}

// File: MyClass.java
class MyClass {
	public static void main(String args[]) {
		System.out.println("Hello, World");
	}
}